package com.jianyun.jyzs.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.StringAdapter;
import com.jianyun.jyzs.bean.EPrijectImages;
import com.jianyun.jyzs.bean.EngProjectLocResult;
import com.jianyun.jyzs.bean.EngineerProjectResult;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.EngLocationDao;
import com.jianyun.jyzs.dao.EngProjectDao;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.BannerLayout;
import com.jrmf360.rylib.common.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangshijun on 2018/5/31.
 * 工程项目详情
 */

public class EngineerProjectDetialActivity extends AppCompatActivity {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.banner)
    BannerLayout banner;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.beginDate)
    TextView beginDate;
    @BindView(R.id.endDate)
    TextView endDate;
    @BindView(R.id.tv_enterprise)
    TextView tvEnterprise;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_note)
    TextView tvNote;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private EngProjectDao dao;
    private String projectid;
    private EngLocationDao dao1;
    private StringAdapter adapter;
    private List<String> listStr = new ArrayList<>();
    private ArrayList<String> banners;
    private String enterpriseCode;
    public EngineerProjectDetialActivity context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_engineer_p_detial);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
    }

    private void initData() {

        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        projectid = getIntent().getStringExtra(SysConstant.msg_key_string1);
        dao = new EngProjectDao(this);
        dao1 = new EngLocationDao(this);
        context=this;
        EngineerProjectResult.EngProject eng = dao.getEngineerByid(projectid);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new StringAdapter(this, listStr);
        recyclerView.setAdapter(adapter);
        if (eng != null) {
            //数据库有数据展示
            setDetialView(eng.getAutoId());
        } else {
            //请求数据到本地
//            ToastUtil.showNoWaitToast(context, "请求数据到本地");
            try {
                updateDateP1(eng.getAutoId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void setDetialView(int autoId) {
        banners = new ArrayList<>();
        banners.add("xxxxxx");
       // banner.setViewUrls(banners);
        setBannerList(projectid + "");
        EngineerProjectResult.EngProject eng = dao.getEngineerByid(projectid);
        tvName.setText(eng.getProJectName());
        topText.setText(eng.getProJectName());
        beginDate.setText(eng.getBeginTime());
        endDate.setText(eng.getEndTime());
        tvEnterprise.setText(eng.getEnterpriseName());
        tvAddress.setText(eng.getProJectAddress());
        tvNote.setText(eng.getNote());
        setP2DetialView(eng.getAutoId() + "");

    }

    private void setBannerList(String s) {
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "GetMainProJectImg");
        map.put("ProJectId", s);
        map.put("PageIndex", "1");
        map.put("Width","480");
        map.put("Height","960");
        map.put("appCode", "jyzs");
        map.put("appType", "Android");
        map.put("appVersion", "1.0.2");
        Log.i("test","map:"+map.toString());
        Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
        api.getNewDynamicImages(map).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        try {
                            Gson gson = new Gson();
                            String s1 = gson.toJson(o);
                            JSONObject jsonObject = new JSONObject(s1);
                            if (jsonObject.getBoolean("result")){
                                String lists = jsonObject.getString("list");
                                if (lists==null ||TextUtils.isEmpty(lists)){
                                    EPrijectImages listBean = gson.fromJson(lists, EPrijectImages.class);
                                    List<EPrijectImages.ListBean> list = listBean.getList();
                                    if (list!=null&&list.size()>0){
                                        banners.clear();
                                        for (EPrijectImages.ListBean el:list
                                                ) {
                                            banners.add(el.getImgUrl());
                                        }
                                        banner.setViewUrls(banners);
                                    }
                                }else {

                                }
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                        Log.i("test","工程项目图片："+o.toString());
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                });

    }

    private void setP2DetialView(String p2id) {
        List<EngProjectLocResult.EngTypeLocBean> engineer = dao1.getEngineer(p2id);
        if (engineer.size() > 0) {
            for (EngProjectLocResult.EngTypeLocBean ee : engineer) {
                listStr.add(ee.getPosition());
            }
            adapter.setList(listStr);
        } else {
            updateDateP2(p2id);
        }
    }

    private void updateDateP2(final String s) {
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "GetProJectPostionList");
        map.put("ProJectId", s);
        map.put("enterpriseCode", enterpriseCode);
        map.put("appCode", "jyzs");
        map.put("appType", "Android");
        map.put("appVersion", "1.0.2");
        Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
        api.getNewEngineerLoc(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<EngProjectLocResult>() {
                    @Override
                    protected void onResponse(EngProjectLocResult response) {
                        if (response.isResult()) {
                            List<EngProjectLocResult.EngTypeLocBean> list = response.getList();
                            for (EngProjectLocResult.EngTypeLocBean ee : list) {
                                dao1.insert(ee);
                            }
                            setP2DetialView(s);
                        } else {
                            ToastUtil.showNoWaitToast(context, response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        ToastUtil.showNoWaitToast(context, msg);
                    }
                });

    }

    //项目目录级别1
    private void updateDateP1(final int autoId) {
        Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("enterpriseCode", enterpriseCode);
        map.put("method", "GetProJectList");
        map.put("pageIndex", "1");
        map.put("appCode", "jyzs");
        map.put("appType", "Android");
        map.put("appVersion", "1.0.2");
        api.getNewEngineerProject(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<EngineerProjectResult>() {
                    @Override
                    protected void onResponse(EngineerProjectResult response) {
                        if (response.isResult()) {
                            List<EngineerProjectResult.EngProject> list = response.getList();
                            for (EngineerProjectResult.EngProject ep : list
                                    ) {
                                dao.insert(ep);
                            }
                            setDetialView(autoId);
                        } else {
                            ToastUtil.showNoWaitToast(context, response.getMessage());
                            setDetialView(autoId);
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        ToastUtil.showNoWaitToast(context, msg);
                        setDetialView(autoId);
                    }
                });
    }

    @OnClick(R.id.topBack)
    public void onViewClicked() {
        finish();
    }
}
